import os
import sys
import time
import base64
import requests
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap, QIcon
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QLabel, QFrame, \
    QLineEdit, QHBoxLayout, QMessageBox, QScrollArea, QGridLayout, QSpinBox, QDialog, QTableWidget, \
    QHeaderView, QTableWidgetItem, QCheckBox, QComboBox, QTabWidget
from io import BytesIO
from fastApi.database.base import get_db, products

from .llm_window import LLMWidget

class ProductCard(QFrame):
    def __init__(self, product_data, parent=None):
        super().__init__(parent)
        self.product_data = product_data
        self.parent_widget = parent
        self.init_ui()
        self.setFixedSize(250, 320)
        self.setFrameStyle(QFrame.Box)
        self.setStyleSheet("""
            QFrame {
                background-color: white;
                border-radius: 10px;
            }
            QFrame:hover {
                border: 2px solid #ff5f00;
            }
        """)
        self.setCursor(Qt.PointingHandCursor)

    def init_ui(self):
        icon = QIcon('./images/购物.png')
        self.setWindowIcon(icon)
        mainLayout = QVBoxLayout()

        self.image_label = QLabel()
        self.image_label.setFixedSize(220, 150)
        self.image_label.setAlignment(Qt.AlignCenter)
        self.image_label.setStyleSheet("""
            QLabel {
                border: 2px solid #f9f9f9;
                border-radius: 8px;
                background-color: #f9f9f9;
                color: #999;
                font-size: 12px;
            }
        """)
        self.load_product_image()
        mainLayout.addWidget(self.image_label)

        name_label = QLabel(self.product_data.get('name', '未知商品'))
        name_label.setStyleSheet("""
            QLabel {
                font-family: Arial;
                font-size: 15px;
                font-weight: bold;
                border: 1px solid white;
                margin: 2px 0;
            }
        """)
        name_label.setWordWrap(True)
        name_label.setMaximumHeight(40)
        mainLayout.addWidget(name_label)

        price_label = QLabel(f"¥{self.product_data.get('price', 0):.2f}")
        price_label.setStyleSheet("""
            font-family: Arial;
            font-size: 18px;
            font-weight: bold;
            border: 1px solid white;
            color: red;
            margin: 2px 0;
        """)
        price_label.setMaximumHeight(40)
        mainLayout.addWidget(price_label)

        self.setLayout(mainLayout)

    def load_product_image(self):
        image_base64 = self.product_data.get('image_base64')
        if image_base64:
            try:
                image_data = base64.b64decode(image_base64)
                pixmap = QPixmap()
                pixmap.loadFromData(image_data)
                if not pixmap.isNull():
                    self.image_label.setPixmap(pixmap.scaled(220, 150, Qt.KeepAspectRatio, Qt.SmoothTransformation))
                    self.image_label.setScaledContents(True)
                    return
                else:
                    print(f"产品 {self.product_data.get('id', 0)} 的图片数据无效")
            except Exception as e:
                print(f"产品 {self.product_data.get('id', 0)} 的 Base64 图片解码失败: {e}")
        self.image_label.setText("暂无图片")

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.show_details()

    def show_details(self):
        detail_dialog = QDialog(self)
        detail_dialog.setWindowTitle(self.product_data.get('name', '商品详情'))
        detail_dialog.resize(400, 400)

        layout = QVBoxLayout()

        image_label = QLabel()
        image_label.setFixedSize(300, 200)
        image_label.setAlignment(Qt.AlignCenter)
        image_base64 = self.product_data.get('image_base64')
        if image_base64:
            try:
                image_data = base64.b64decode(image_base64)
                pixmap = QPixmap()
                pixmap.loadFromData(image_data)
                if not pixmap.isNull():
                    image_label.setPixmap(pixmap.scaled(300, 200, Qt.KeepAspectRatio, Qt.SmoothTransformation))
                    image_label.setScaledContents(False)
                else:
                    print(f"产品 {self.product_data.get('id', 0)} 的图片数据无效")
            except Exception as e:
                print(f"产品 {self.product_data.get('id', 0)} 的 Base64 图片解码失败: {e}")
        else:
            image_label.setText("暂无图片")
        layout.addWidget(image_label)

        name_label = QLabel(f"名称: {self.product_data.get('name', '未知')}")
        name_label.setStyleSheet("font-size: 16px; font-weight: bold;")
        layout.addWidget(name_label)

        price_label = QLabel(f"价格: ¥{self.product_data.get('price', 0):.2f}")
        price_label.setStyleSheet("font-size: 14px;")
        layout.addWidget(price_label)

        quantity_label = QLabel(f"库存: {self.product_data.get('quantity', 0)}")
        quantity_label.setStyleSheet("font-size: 14px;")
        layout.addWidget(quantity_label)

        description_label = QLabel(f"描述: {self.product_data.get('description', '无描述')}")
        description_label.setStyleSheet("font-size: 14px;")
        description_label.setWordWrap(True)
        layout.addWidget(description_label)

        # 添加数量选择
        quantity_layout = QHBoxLayout()
        quantity_spin = QSpinBox()
        quantity_spin.setMinimum(1)
        quantity_spin.setMaximum(self.product_data.get('quantity', 1))
        quantity_spin.setValue(1)
        quantity_spin.setStyleSheet("""
            QSpinBox {
                padding: 5px;
                border: 2px solid #ddd;
                border-radius: 5px;
                font-size: 14px;
            }
        """)
        quantity_layout.addWidget(QLabel("数量:"))
        quantity_layout.addWidget(quantity_spin)
        layout.addLayout(quantity_layout)

        # 加入购物车按钮
        add_cart_button = QPushButton("加入购物车")
        add_cart_button.setStyleSheet("""
            QPushButton {
                background-color: #ff5f00;
                color: white;
                padding: 10px;
                border-radius: 5px;
                font-size: 14px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #e65b00;
            }
        """)
        add_cart_button.clicked.connect(lambda: self.add_to_cart(self.product_data, quantity_spin.value()))
        layout.addWidget(add_cart_button)

        layout.addStretch()
        detail_dialog.setLayout(layout)
        detail_dialog.exec_()

    def add_to_cart(self, product, quantity):
        """将商品加入购物车并检查库存"""
        if self.parent_widget:
            if product['quantity'] <= 0:
                QMessageBox.warning(self, "错误", f"{product['name']} 库存不足，无法加入购物车。")
                return
            self.parent_widget.add_to_cart(product, quantity)

class ShoppingCart(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.parent = parent
        self.setWindowTitle("购物车")
        self.resize(600, 500)
        self.checkboxes = []
        self.init_ui()

    def init_ui(self):
        icon = QIcon('./images/购物.png')
        self.setWindowIcon(icon)
        layout = QVBoxLayout()

        title = QLabel("我的购物车")
        title.setStyleSheet("""
                 font-family: 宋体;
                 font-size: 16px;
                 font-weight: bold;
        """)
        layout.addWidget(title)

        self.cart_table = QTableWidget()
        self.cart_table.setColumnCount(6)
        self.cart_table.setHorizontalHeaderLabels(["选择", "商品名称", "单价", "数量", "小计", "操作"])

        self.cart_table.setEditTriggers(QTableWidget.NoEditTriggers)
        self.cart_table.setSelectionMode(QTableWidget.NoSelection)
        self.cart_table.setFocusPolicy(Qt.NoFocus)

        header = self.cart_table.horizontalHeader()
        header.setSectionResizeMode(0, QHeaderView.ResizeToContents)
        header.setSectionResizeMode(1, QHeaderView.Stretch)
        header.setSectionResizeMode(2, QHeaderView.ResizeToContents)
        header.setSectionResizeMode(3, QHeaderView.ResizeToContents)
        header.setSectionResizeMode(4, QHeaderView.ResizeToContents)
        header.setSectionResizeMode(5, QHeaderView.ResizeToContents)
        layout.addWidget(self.cart_table)

        self.total_label = QLabel("总计: ￥0.00")
        self.total_label.setStyleSheet("""
                         font-family: 宋体;
                         font-size: 14px;
                         font-weight: bold;
                         color: #e74c3c;
                """)
        self.total_label.setAlignment(Qt.AlignRight)
        layout.addWidget(self.total_label)

        button = QHBoxLayout()
        self.select_all_checkbox = QCheckBox("全选")
        self.select_all_checkbox.stateChanged.connect(self.on_select_all_changed)
        button.addWidget(self.select_all_checkbox)

        clear_btn = QPushButton("清空购物车")
        clear_btn.setCursor(Qt.PointingHandCursor)
        clear_btn.setStyleSheet("""
                    QPushButton {
                        background-color: #ff5f00;
                        color: white;
                        padding: 10px 20px;
                        border-radius: 5px;
                        font-size: 14px;
                        font-weight: bold;
                    }
                """)
        clear_btn.clicked.connect(self.clear_cart)
        button.addWidget(clear_btn)

        checkout_btn = QPushButton("结算选中商品")
        checkout_btn.setCursor(Qt.PointingHandCursor)
        checkout_btn.setStyleSheet("""
                    QPushButton {
                        background-color: #ff5f00;
                        color: white;
                        padding: 10px 20px;
                        border-radius: 5px;
                        font-size: 14px;
                        font-weight: bold;
                    }
                """)
        checkout_btn.clicked.connect(self.checkout)
        button.addWidget(checkout_btn)

        layout.addLayout(button)
        self.setLayout(layout)
        self.update_cart_display()

    def update_cart_display(self):
        if self.parent:
            selected_keys = {product_key for product_key, checkbox in self.checkboxes if checkbox.isChecked()}
            cart_items = self.parent.cart_items
            self.cart_table.setRowCount(len(cart_items))
            self.checkboxes.clear()

            for _, checkbox in self.checkboxes:
                try:
                    checkbox.stateChanged.disconnect()
                except:
                    pass

            for row, (product_key, (product, quantity)) in enumerate(cart_items.items()):
                checkbox = QCheckBox()
                checkbox.stateChanged.connect(self.update_checkbox_states)
                self.checkboxes.append((product_key, checkbox))
                self.cart_table.setCellWidget(row, 0, checkbox)

                self.cart_table.setItem(row, 1, QTableWidgetItem(product['name']))
                self.cart_table.setItem(row, 2, QTableWidgetItem(f"¥{product['price']:.2f}"))
                self.cart_table.setItem(row, 3, QTableWidgetItem(str(quantity)))
                subtotal = product['price'] * quantity
                self.cart_table.setItem(row, 4, QTableWidgetItem(f"¥{subtotal:.2f}"))

                remove_button = QPushButton("移除")
                remove_button.clicked.connect(lambda checked, p_key=product_key: self.remove_item_by_key(p_key))
                self.cart_table.setCellWidget(row, 5, remove_button)

            self.update_total()
            self.update_checkbox_states()

    def update_checkbox_states(self):
        all_checked = all(checkbox.isChecked() for _, checkbox in self.checkboxes)
        self.select_all_checkbox.blockSignals(True)
        self.select_all_checkbox.setChecked(all_checked)
        self.select_all_checkbox.blockSignals(False)
        self.update_total()

    def update_total(self):
        total = sum(product['price'] * quantity for product_key, (product, quantity) in self.parent.cart_items.items()
                   if any(key == product_key and checkbox.isChecked() for key, checkbox in self.checkboxes))
        self.total_label.setText(f"总计: ￥{total:.2f}")

    def on_select_all_changed(self, state):
        checked = state == Qt.Checked
        for _, checkbox in self.checkboxes:
            checkbox.setChecked(checked)
        self.update_total()

    def remove_item_by_key(self, product_key):
        if self.parent:
            if product_key in self.parent.cart_items:
                del self.parent.cart_items[product_key]
                self.update_cart_display()
                self.parent.update_cart_count()

    def clear_cart(self):
        self.parent.cart_items.clear()
        self.update_cart_display()
        self.parent.update_cart_count()

    def checkout(self):
        db = get_db()
        total_amount = 0
        user_name = self.parent.user_info.get('username', '用户1') if self.parent.user_info else '用户1'
        user_email = self.parent.user_info.get('email', 'user1@example.com') if self.parent.user_info else 'user1@example.com'
        for product_key, (product, quantity) in self.parent.cart_items.items():
            # 更新库存
            new_quantity = product['quantity'] - quantity
            if new_quantity < 0:
                QMessageBox.warning(self, "错误", f"{product['name']} 库存不足，无法结算。")
                return
            db.operation_sql(
                "UPDATE products SET quantity = ? WHERE id = ?",
                [new_quantity, product['id']]
            )
            # 记录订单
            db.operation_sql(
                "INSERT INTO orders (customer_name, customer_email, order_date, product_id, quantity, price) VALUES (?, ?, ?, ?, ?, ?)",
                [user_name, user_email, time.strftime("%Y-%m-%d %H:%M:%S"), product['id'], quantity, product['price']]
            )
            total_amount += product['price'] * quantity
            # 更新内存中的产品数据
            product['quantity'] = new_quantity

        db.commit()  # 提交事务
        QMessageBox.information(self, "成功", f"结算完成，总额：¥{total_amount:.2f}")
        self.parent.cart_items.clear()
        self.parent.update_cart_count()
        self.close()
        self.parent.load_products()  # 重新加载产品数据

class ShoppingWindow(QWidget):
    def __init__(self, parent=None, user_info=None):
        super().__init__()
        self.parent = parent
        self.user_info = user_info  # 存储用户身份信息
        self.cart_items = {}
        self.init_ui()

    def init_ui(self):
        self.setWindowTitle('购物商城')
        self.setGeometry(100, 100, 1200, 800)
        icon = QIcon('./images/购物.png')
        self.setWindowIcon(icon)

        layout = QVBoxLayout()
        layout.setContentsMargins(10, 10, 10, 10)
        layout.setSpacing(10)

        self.tab_widget = QTabWidget()
        self.tab_widget.setStyleSheet("""
            QTabWidget::pane {
                border: 1px solid #ccc;
                background-color: #f8f8f8;
            }
            QTabBar::tab {
                background: #e0e0e0;
                border: 1px solid #ccc;
                padding: 8px 12px;
                border-top-left-radius: 4px;
                border-top-right-radius: 4px;
            }
            QTabBar::tab:selected {
                background: #ffffff;
                border-bottom-color: #ffffff;
            }
        """)

        # 商品浏览标签页
        self.product_browse_widget = QWidget()
        product_browse_layout = QVBoxLayout()
        self.create_top_bar(product_browse_layout)
        self.create_search_frame(product_browse_layout)
        self.create_productsScrollArea(product_browse_layout)
        self.create_cart_button(product_browse_layout)
        self.product_browse_widget.setLayout(product_browse_layout)
        self.tab_widget.addTab(self.product_browse_widget, "商品浏览")

        # AI客服标签页
        self.ai_assistant = LLMWidget(is_admin=False)  # 使用现有 LLMWidget
        self.tab_widget.addTab(self.ai_assistant, "AI客服")

        layout.addWidget(self.tab_widget)
        self.setLayout(layout)
        self.load_products()

    def create_top_bar(self, main_layout):
        topBar = QFrame()
        topBar.setStyleSheet("""
            QFrame {
                background-color: #ff5f00;
                border-radius: 8px;
                padding: 10px;
            }
        """)
        topLayout = QHBoxLayout()

        welcome_label = QLabel(f"欢迎光临购物商城, {self.user_info.get('username', '用户')}")
        welcome_label.setStyleSheet("color: white; font-size: 25px; font-weight: bold; font-family: Microsoft YaHei;")

        logout_btn = QPushButton("退出")
        logout_btn.setCursor(Qt.PointingHandCursor)
        logout_btn.setStyleSheet("""
            QPushButton {
                background-color: white;
                color: #ff5f00;
                padding: 10px 20px;
                border-radius: 5px;
                font-size: 14px;
                font-weight: bold;
            }
        """)
        logout_btn.clicked.connect(self.logout)

        topLayout.addWidget(welcome_label)
        topLayout.addStretch()
        topLayout.addWidget(logout_btn)

        topBar.setLayout(topLayout)
        main_layout.addWidget(topBar)

    def create_search_frame(self, main_layout):
        searchFrame = QFrame()
        searchFrame.setStyleSheet("""
            background-color: #f8f9fa;
            border-radius: 5px;
            padding: 3px
        """)
        searchLayout = QHBoxLayout()

        imageLabel = QLabel(self)
        imageLabel.setFixedSize(100, 50)
        imageLabel.setPixmap(QPixmap('./images/购物2.png'))
        imageLabel.setScaledContents(True)
        searchLayout.addWidget(imageLabel)

        self.searchInput = QLineEdit()
        self.searchInput.setPlaceholderText(" 搜索商品...")
        self.searchInput.setStyleSheet("""
            QLineEdit {
                padding: 10px;
                border: 2px solid #ddd;
                border-radius: 10px;
                font-size: 20px;
                background-color: white;
                border-color: #ff5f00;
            }
        """)
        self.searchInput.textChanged.connect(self.filter_products)
        searchLayout.addWidget(self.searchInput)

        self.category_combo = QComboBox()
        self.category_combo.addItems(["全部", "电子产品", "衣服"])
        self.category_combo.setStyleSheet("""
        /* 基础样式 */
        QComboBox {
            background-color: white;
            border: 2px solid #ff5f00;
            border-radius: 10px;
            padding: 10px;
            font-size: 20px;
            min-width: 50px;
            selection-background-color: #ff5f00;
            selection-color: white;
        }

        /* 下拉按钮区域 */
        QComboBox::drop-down {
            subcontrol-origin: padding;
            subcontrol-position: center right;
            width: 30px;
            border-left: 1px solid #ddd;
            border-top-right-radius: 10px;
            border-bottom-right-radius: 10px;
            background-color: white;
        }

        /* 下拉箭头 */
        QComboBox::down-arrow {
            image: url(./images/down_arrow.png);
            width: 14px;
            height: 14px;
        }

        /* 下拉列表 */
        QComboBox QAbstractItemView {
            border: 2px solid #ff5f00;
            border-radius: 10px;
            background-color: white;
            selection-background-color: white;
            selection-color:  #ff5f00;
            outline: 0;
            padding: 5px;
            margin: 0; /* 移除默认边距 */
        }

        /* 下拉列表项 */
        QComboBox QAbstractItemView::item {
            height: 30px;
            padding: 5px 10px;
            background-color: white;
        }

        /* 下拉列表项悬停效果 */
        QComboBox QAbstractItemView::item:hover {
            background-color: #fff9f5;
            color: #ff5f00;
        }


        """)
        self.category_combo.currentTextChanged.connect(self.filter_products)
        searchLayout.addWidget(self.category_combo)

        searchFrame.setLayout(searchLayout)
        main_layout.addWidget(searchFrame)

    def create_productsScrollArea(self, mainLayout):
        productsScrollArea = QScrollArea()
        productsScrollArea.setWidgetResizable(True)
        productsScrollArea.setStyleSheet("""
            border: 2px solid #ddd;
            background-color: white;
            border-radius: 15px;
        """)

        self.products_container = QWidget()
        self.products_layout = QGridLayout()
        self.products_layout.setSpacing(15)
        self.products_container.setLayout(self.products_layout)

        productsScrollArea.setWidget(self.products_container)
        mainLayout.addWidget(productsScrollArea)

    def create_cart_button(self, main_layout):
        self.cartButton = QPushButton(f"🛒 购物车 (0)")
        self.cartButton.setCursor(Qt.PointingHandCursor)
        self.cartButton.setStyleSheet("""
            QPushButton {
                background-color: #ff5f00;
                color: white;
                padding: 10px 20px;
                border-radius: 5px;
                font-size: 14px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #e65b00;
            }
        """)
        self.cartButton.clicked.connect(self.show_cart)
        main_layout.addWidget(self.cartButton)

    def filter_products(self):
        search_text = self.searchInput.text().lower()
        selected_category = self.category_combo.currentText()
        self.filtered_product = []

        for product in self.all_products:
            if search_text and search_text not in product['name'].lower():
                continue
            if selected_category == "电子产品" and product['category_id'] != 1:
                continue
            if selected_category == "衣服" and product['category_id'] != 2:
                continue
            # 保留所有字段，但只用于图片加载
            self.filtered_product.append(product)

        self.update_product_display()

    def update_product_display(self):
        for i in reversed(range(self.products_layout.count())):
            child = self.products_layout.itemAt(i).widget()
            if child:
                child.setParent(None)
        row, col = 0, 0
        max_cols = 4

        for product in self.filtered_product:
            card = ProductCard(product, self)
            self.products_layout.addWidget(card, row, col)
            col += 1
            if col >= max_cols:
                col = 0
                row += 1

    def load_products(self, products=[]):
        db = get_db()
        self.all_products = db.selectData(
            "SELECT id, name, description, price, quantity, category_id, image_base64 FROM products")
        # 仅在调试模式下输出，建议注释或移除
        # import os
        # if os.getenv("DEBUG", "False").lower() == "true":
        #     print(f"加载的产品数据: {self.all_products}")
        self.filter_products()

    def show_cart(self):
        cart_dialog = ShoppingCart(self)
        cart_dialog.exec_()

    def add_to_cart(self, product, quantity):
        if product['quantity'] <= 0:
            QMessageBox.warning(self, "错误", f"{product['name']} 库存不足，无法加入购物车。")
            return
        product_key = f"{product['id']}_{product['name']}"
        if product_key in self.cart_items:
            current_quantity = self.cart_items[product_key][1]
            if current_quantity + quantity > product['quantity']:
                QMessageBox.warning(self, "错误", f"{product['name']} 库存不足，最大可加入 {product['quantity'] - current_quantity} 件。")
                return
            self.cart_items[product_key] = (product, current_quantity + quantity)
        else:
            self.cart_items[product_key] = (product, quantity)
        self.update_cart_count()
        QMessageBox.information(self, "成功", f"已将{product['name']} x {quantity} 加入购物车")

    def update_cart_count(self):
        total_items = sum(quantity for _, quantity in self.cart_items.values())
        self.cartButton.setText(f"🛒 购物车 ({total_items})")

    def logout(self):
        self.close()
        self.parent.clear_inputs()  # 清空输入框
        self.parent.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    # 模拟用户登录信息
    user_info = {"username": "测试用户", "email": "test@example.com"}
    window = ShoppingWindow(None, user_info)
    window.show()
    sys.exit(app.exec_())